

window.commonMethods  = {
  data() {
    return {
      multipleSelection: [],
      visibleColumns: [],
      showColumnSetting: false,
      checkList: [],
      isIndeterminate: false,
      isAllChecked: false,
      listQuery: {
        page: 1,
        limit: 10,
      },
      listLoading: false,
      el_table_column: [],
      form_fields: [],
      search_fields: [],
      list: [],
      total: 0,
      searchForm: {},
      uploadLists:{}
    };
  },
  mounted() {
    //console.log('commonMethods mounted')
  },
  methods: {
    getTagConfig(item, row) {
      const value = row[item.prop]; // 可能是字符串、数字、null 等
      if (!Array.isArray(item.tags)) {
        return null;
      }

      // 查找 tags 中 value 匹配的项
      const matchedTag = item.tags.find(tag => {
        // 注意：要处理类型差异，比如 '1' 和 1，可以使用宽松相等 ==
        return tag.value == value;
      });

      return matchedTag || {
        label: '未知',
        type: 'info',
        color: ''
      };
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },

    updateVisibleColumns() {
      this.visibleColumns = this.el_table_column.filter(column => this.checkList.includes(column.label));
    },

    closeVisibleColumns() {
      this.showColumnSetting = false;
    },

    handleCheckAllChange(val) {
      this.checkList = val ? this.el_table_column.map(column => column.label) : [];
      this.isIndeterminate = false;
      this.updateVisibleColumns();
    },

    handleDateChange(fieldName) {
      console.log(`Date range changed for ${fieldName}:`, this.searchForm[fieldName]);
      this.search();
    },

    handleCheckedColumnsChange(value) {
      const checkedCount = value.length;
      this.isAllChecked = checkedCount === this.el_table_column.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.el_table_column.length;
    },

    sizeChange(size) {
      this.listQuery.limit = size;
      this.listQuery.page = 1;
      this.fetchData();
    },

    search() {
      this.listQuery.page = 1;
      Object.assign(this.listQuery, this.searchForm);
      this.fetchData(true);
    },
    fetchListConfig(){
      get(api_base + '/list_config').then(res => {
          this.el_table_column = res.data.el_table_column;
            if (res.data.form_fields && res.data.form_fields.length > 0) {
            this.form_fields = res.data.form_fields;
          }
          this.search_fields = res.data.search_fields;
          this.checkList = []; // 重置
          this.el_table_column.forEach(column => this.checkList.push(column.label));
          this.updateVisibleColumns();
      });
    },
    fetchData(isSearch) {
      this.listLoading = true;
      get(api_base + '/list', this.listQuery).then(res => {
        this.list = res.data.list;
        this.total = res.data.total;
        this.listLoading = false;
      });
    },

    del(row) {
      this.$confirm('此操作将删除此数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(api_base + '/delete', { id: row.id }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          });
          this.fetchData();
        });
      }).catch(() => {});
    },
    goBack() {
      history.back();
    },
    // 跳转
    goUrl(url, params){
       if (params && Object.keys(params).length > 0) {
          let query = new URLSearchParams(params).toString();
          if (url.includes('?')) {
              url += '&' + query;
          } else {
              url += '?' + query;
          }
      }
      location.href = url;
    },
    // 获取 URL 参数
    getParams(name) {
        const queryString = window.location.search.substring(1);
        const params = {};

        if (!queryString) {
            return name ? null : params;
        }

        queryString.split('&').forEach(function (pair) {
            const [key, value] = pair.split('=');
            params[decodeURIComponent(key)] = decodeURIComponent(value || '');
        });
        if (name) {
            return params.hasOwnProperty(name) ? params[name] : null;
        }
        return params;
    },

    handleButtonClick(row, button) {
      console.log(row, button)
      let action = button.action;
      //TODO 请自定义不存在的按钮处理逻辑
      try {
        if (action === 'del') {
          this.del(row);
        } else if (action === 'edit') {
          this.edit(row);
        } else if (action === 'add') {
          this.add();
        } else if (action === 'view') {
          this.view(row);
        } else if (action === 'export') {
          this.export(row);
        } else if (action === 'import') {
          this.import(row);
        } else if (action === 'print') {
          this.print(row);
        }
      } catch (e) {
        console.log('按钮处理逻辑不存在：', action, e)
        this.$message.error('按钮处理逻辑不存在：' + action)
      }
    }
  }
};
